<template>
  <div :id="id" :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import echarts from "echarts";
import resize from "./mixins/resize";
import { getRectData } from "@/api/chart";
import { notify } from "@/utils/message";

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart",
    },
    id: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "200px",
    },
    height: {
      type: String,
      default: "200px",
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  mounted() {
    this.initChart();
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart() {
      this.chart = echarts.init(document.getElementById(this.id));
      this.chart.setOption(
        getRectData()
          .then((res) => {
            notify(1, "获取直方图数据");
            console.log();
            // 1. 转换数据格式
            const data = [["price", "amount", "product"]].concat(
              res.data.data.map((item) => [
                item.price,
                item.author1,
                item.author2,
              ])
            );
            console.log(data);
            // 2. 绘制图表
            this.chart.setOption({
              title: {
                text: "作者与出版图书价格分布",
                subtext: "范围（排名前十）",
                left: "center",
              },
              dataset: {
                source: data,
              },
              grid: { containLabel: true },
              xAxis: { name: "图书价格（元）" },
              yAxis: { name: "作者名", type: "category" },
              tooltip: {
                valueFormatter: function (value) {
                  return value + " 元";
                },
              },
              visualMap: {
                orient: "horizontal",
                left: "center",
                min: 500,
                max: 2500,
                text: ["高价（元）", "低价（元）"],
                dimension: 0,
                inRange: {
                  color: ["#65B581", "#FFCE34", "#FD665F"],
                },
              },
              series: [
                {
                  type: "bar",
                  encode: {
                    // Map the "amount" column to X axis.
                    x: "图书数量（本）",
                    // Map the "product" column to Y axis
                    y: "product",
                  },
                },
              ],
            });
          })
          .catch((err) => {
            notify(2, "获取直方图数据");
          })
      );
    },
  },
};
</script>
